import { Node, UITransform, Layers, SpriteFrame, AnimationClip, animation, Sprite, AnimationComponent } from 'cc'
import ResourceCenter from '../Runtime/ResourceCenter'

//创建ui节点
export const createUINode = (name: string = '') => {
  const node = new Node(name)
  const transform = node.addComponent(UITransform)
  transform.setAnchorPoint(0, 1)
  node.layer = Layers.Enum.UI_2D

  return node
}

//给组件初始化动画
export const initAnimation = (component: AnimationComponent, spriteFrames: SpriteFrame[], animationSpeed: number) => {
  //创建动画剪辑
  const animationClip = new AnimationClip()
  //创建一个对象轨道
  const track = new animation.ObjectTrack()
  //设置对象轨道的路径
  track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame')
  //设置对象轨道的曲线
  const frames: [number, SpriteFrame][] = spriteFrames.map((spriteFrame, index) => {
    return [index * animationSpeed, spriteFrame]
  })

  //为曲线添加关键帧
  track.channel.curve.assignSorted(frames)
  //将对象轨道添加到动画剪辑中
  animationClip.addTrack(track)
  // 整个动画剪辑的周期
  animationClip.duration = animationSpeed * frames.length

  return {
    play(wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal) {
      // 设置动画剪辑的循环模式
      animationClip.wrapMode = wrapMode
      //将动画剪辑添加到动画组件中
      component.defaultClip = animationClip
      //播放动画
      component.play()
    },
  }
}
